package com.dkm.orproject.utils.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Set;

@Component
public class RedisUtil {

    Logger logger = LoggerFactory.getLogger(getClass());

    private static RedisTemplate template;

    /**
     * 静态注入
     */
    public RedisUtil(RedisTemplate redisTemplate) {
        RedisUtil.template = redisTemplate;
    }

    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */
    public Object get(String key) {

        return key == null ? null : template.opsForValue().get(key);
    }

    /**
     * 普通缓存放入
     *
     * @param key  键
     * @param value 值
     * @return true成功 false失败
     */
    public boolean set(String key, Object value) {
        logger.error("正在加入缓存:"+key);
        try {
            template.opsForValue().set(key,  value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 删除前缀是prex的所有key
     * @param prex
     */
    public void deleteByPrex(String prex) {
        logger.info("正在删除缓存"+prex);
        Set<String> keys = template.keys(prex+"*");
        logger.info("正在删除缓存"+keys.size());
        if (!CollectionUtils.isEmpty(keys)) {
            template.delete(keys);
        }
    }

}
